using System;
using System.Xml;
using System.Collections.Specialized;


namespace UnitLite.Util
{
	/// <summary>
	/// AppSettingsDocument Read and Write from the App.config file in the UnitLite intallation folder.
	/// </summary>
	public class AppSettingsDocument
	{
        private string AppFullName = string.Empty;

        public AppSettingsDocument(string AppFullName_)
        {
            AppFullName = AppFullName_;
        }

		public string GetValue(string appKey)
		{
			try
			{
				XmlDocument xDoc = new XmlDocument();

                xDoc.Load(AppFullName);
				XmlNode xNode = xDoc.SelectSingleNode("//appSettings");
				XmlElement xElem = (XmlElement)xNode.SelectSingleNode("//add[@key='" + appKey + "']");
				if (xElem != null)
				{
					return xElem.GetAttribute("value");
				}
			}
			catch (System.Exception e)
			{
				Console.WriteLine(e.Message);
			}

			return String.Empty;
		}

		public void SetValue(string AppKey, string AppValue)
		{
			try
			{
				XmlDocument xDoc = new XmlDocument();
                xDoc.Load(AppFullName);
				XmlNode xNode;
				XmlElement xElement;
		
				xNode = xDoc.SelectSingleNode("//appSettings");
				xElement = (XmlElement)xNode.SelectSingleNode("//add[@key='" + AppKey + "']");
				if (xElement != null)
				{
					xElement.SetAttribute("value", AppValue);
				}
				else
				{
					xElement = xDoc.CreateElement("add");
					xElement.SetAttribute("key", AppKey);
					xElement.SetAttribute("value", AppValue);
					xElement.AppendChild(xElement);
				}

                xDoc.Save(ProjectSettings.AppFullName);
			}
			catch (System.Exception e)
			{
				Console.WriteLine(e.Message);
			}
		}
	}
}
